using System;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 动态生成RenderTexture大小
    /// </summary>
    public class DynamicRenderTexture : MonoBehaviour
    {
        public Camera _camera;
        public string textureName;
        private RenderTexture _renderTexture;
        public bool immediatelyDispose = true;
        public Vector2 rect;
        public int depth;
        private static event Action<string> DisposeEvent;
        
        
        public RenderTexture RenderTextureTemp
        {
            get
            {
                if (_renderTexture == null)
                {
                    _renderTexture = RenderTexture.GetTemporary((int)rect.x, (int)rect.y, depth);
                    _renderTexture.name = textureName;
                }

                if (_camera != null)
                {
                    _camera.targetTexture = _renderTexture;
                }

                return _renderTexture;
            }
        }

        public void Awake()
        {
            var a = RenderTextureTemp;
        }

        private void OnEnable()
        {
            DisposeEvent += OnDispose;
        }

        private void OnDisable()
        {
            if (!immediatelyDispose)
            {
                return;
            }

            Dispose();
            DisposeEvent -= OnDispose;
        }

        private void OnDispose(string name)
        {
            if (_renderTexture != null && name != _renderTexture.name)
            {
                return;
            }

            Dispose();
        }

        public void Dispose()
        {
            if (_camera != null)
            {
                _camera.targetTexture = null;
            }

            RenderTexture.ReleaseTemporary(_renderTexture);
            _renderTexture = null;
        }


        public static void DisposeRenderTexture(string name)
        {
            if (DisposeEvent != null)
            {
                DisposeEvent(name);
            }
        }
    }
}